<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function myWebSocket(url, params) {
            return new Promise((resolve, reject) => {
                const ws = new WebSocket(url)
                ws.onopen = () => {
                    ws.send(JSON.stringify(params))
                    resolve(ws)
                }
                ws.onerror = (e) => {
                    reject(e)
                }
            })
        }
        function sendMessagePeriodically(ws, message, interval = 2000) {
            // 立即发送一次消息
            ws.send(JSON.stringify({ msg: message }));
            // 设置定时器，每隔interval毫秒发送一次消息
            return setInterval(() => {
                ws.send(JSON.stringify({ msg: message }));
            }, interval);
        }
        myWebSocket('ws://127.0.0.1:3000', {})
            .then(ws => {
                const timer = sendMessagePeriodically(ws, 'hello server', 2000);
                ws.onmessage = (e) => {
                    console.log(e.data);
                }
            })
            .catch(e => {
                console.log(e);
            })


    </script>

</body>

</html>